// news-system-modern/src/components/sandbox/TopHeader.tsx
import React, { useState, useEffect } from 'react';
import { Layout, Dropdown, Avatar, Button, message } from 'antd';
import type { MenuProps } from 'antd';
import { MenuUnfoldOutlined, MenuFoldOutlined, UserOutlined, ReloadOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { toggleCollapsed, selectCollapsed } from '../../store/features/collapsedSlice';
import { clearUser } from '../../store/features/userSlice';
import permissionTools from '../../utils/resetPermissions';
import { STORAGE_KEYS } from '../../constants/common';
import './TopHeader.scss';
import type { RootState, UserInfo } from '../../store/types';

const { Header } = Layout;

// API基础URL，应该从配置文件导入，这里直接定义
const API_BASE_URL = process.env.REACT_APP_API_URL || '/adminapi';

/**
 * 简化版获取头像URL的辅助函数
 * 处理头像路径并添加认证令牌
 */
const getAvatarUrl = (url?: string, username?: string) => {
  // 如果没有URL，使用默认头像服务
  if (!url) {
    return `https://api.dicebear.com/7.x/miniavs/svg?seed=${username || 'default'}`;
  }
  
  // 已经是完整URL的情况
  if (url.startsWith('http')) {
    return url;
  }
  
  // 获取认证令牌，移除Bearer前缀
  const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
  const tokenValue = token ? token.replace('Bearer ', '') : '';
  
  // 确保路径开头有斜杠
  let path = url.startsWith('/') ? url : `/${url}`;
  
  // 处理不同格式的路径
  // 如果路径中不包含avataruploads和uploads，添加avataruploads前缀
  if (!path.includes('/avataruploads/') && !path.includes('/uploads/')) {
    path = `/avataruploads${path}`;
  }
  
  // 构建带认证令牌的完整URL
  const baseUrl = `${API_BASE_URL}${path}`;
  
  // 添加token作为查询参数，确保后端可以识别
  return tokenValue ? `${baseUrl}?token=${encodeURIComponent(tokenValue)}` : baseUrl;
};

/**
 * 顶部导航栏组件
 * 显示用户信息、提供侧边栏切换按钮和用户菜单
 */
const TopHeader: React.FC = () => {
  const dispatch = useDispatch();
  
  // 从Redux获取必要状态
  const isCollapsed = useSelector(selectCollapsed);
  
  // 注意：userInfo可能是null，所以需要做非空检查
  const userInfo = useSelector((state: RootState) => 
    state.user?.userInfo
  );
  
  // 用户信息状态
  const [displayName, setDisplayName] = useState<string>('');
  const [displayRole, setDisplayRole] = useState<string>('');
  const [avatarSrc, setAvatarSrc] = useState<string>('');

  // 在组件挂载和userInfo变化时更新用户信息
  useEffect(() => {
    // 从Redux或localStorage获取用户信息
    const setupUserInfo = () => {
      let username = '';
      let role = '';
      let avatar = '';
      
      // 优先使用Redux中的用户信息
      if (userInfo) {
        username = userInfo.username || '';
        role = userInfo.role?.roleName || '';
        avatar = userInfo.avatar || '';
      } 
      // 如果Redux中没有，尝试从localStorage获取
      else {
        try {
          const storedInfo = localStorage.getItem('userInfo');
          if (storedInfo) {
            const parsedInfo = JSON.parse(storedInfo) as Partial<UserInfo>;
            username = parsedInfo.username || '用户';
            role = parsedInfo.role?.roleName || '用户';
            avatar = parsedInfo.avatar || '';
          } else {
            username = '用户';
          }
        } catch (error) {
          console.error('读取用户信息失败:', error);
          username = '用户';
        }
      }
      
      // 更新状态
      setDisplayName(username);
      setDisplayRole(role);
      
      // 设置头像URL
      if (avatar) {
        setAvatarSrc(getAvatarUrl(avatar, username));
      } else {
        // 使用默认头像
        setAvatarSrc(getAvatarUrl(undefined, username));
      }
    };
    
    // 立即执行一次
    setupUserInfo();
    
    // 每次userInfo变化时重新执行
  }, [userInfo]);

  // 处理头像加载错误
  const handleAvatarError = () => {
    // 使用默认头像
    setAvatarSrc(getAvatarUrl(undefined, displayName));
    return true; // 阻止继续尝试加载错误的URL
  };

  // 切换侧边栏折叠状态
  const handleChangeCollapsed = () => {
    dispatch(toggleCollapsed());
  };

  // 退出登录
  const handleLogout = () => {
    try {
      // 清除localStorage中的所有认证相关信息
      localStorage.removeItem(STORAGE_KEYS.TOKEN);
      localStorage.removeItem(STORAGE_KEYS.USER_INFO);
      localStorage.removeItem(STORAGE_KEYS.USER_RIGHTS);
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');
      localStorage.removeItem('sidebarItems');
      
      // 清除Redux状态
      dispatch(clearUser());
      message.success('退出成功');
    } catch (error) {
      console.error('退出时发生错误:', error);
      message.error('退出失败，请重试');
    }
  };
  
  // 重置权限
  const handleResetPermissions = () => {
    const result = permissionTools.resetUserPermissions();
    if (result.success) {
      message.success(result.message);
    } else {
      message.error(result.message);
    }
  };

  // 下拉菜单配置 - 简化菜单
  const items: MenuProps['items'] = [
    {
      key: '0',
      label: <span className="role-name">{displayRole || '用户'}</span>
    },
    {
      type: 'divider'
    },
    {
      key: '1',
      icon: <ReloadOutlined />,
      label: '重置权限',
      onClick: handleResetPermissions
    },
    {
      key: '2',
      danger: true,
      label: '退出系统',
      onClick: handleLogout
    }
  ];

  return (
    <Header className="top-header">
      {/* 侧边栏折叠按钮 */}
      <Button
        type="text"
        icon={isCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        onClick={handleChangeCollapsed}
        className="trigger-button"
      />

      {/* 用户信息区域 */}
      <div className="user-info">
        <span className="welcome-text">
          欢迎<span className="username">{displayName || '用户'}</span>回来
        </span>
        <Dropdown menu={{ items }} placement="bottomRight">
          <Avatar 
            className="avatar"
            size="large" 
            icon={<UserOutlined />}
            src={avatarSrc}
            alt={`${displayName || '用户'}的头像`}
            onError={handleAvatarError}
          />
        </Dropdown>
      </div>
    </Header>
  );
};

export default TopHeader;